package com.college_career_system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.college_career_system.pojo.dto.UserDTO;
import com.college_career_system.pojo.po.User;
import com.college_career_system.dao.UserMapper;
import com.college_career_system.pojo.vo.SubmitDetail;
import com.college_career_system.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.college_career_system.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Empty
 * @since 2022-12-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public JSONObject addUser(UserDTO stu) {
        if (stu == null || stu.getUid() == null){
            return ResponseResult.failure(ResponseCode.STATUS_ERROR);
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("uid",stu.getUid())
                .eq("school",stu.getSchool());
        if (userMapper.selectCount(wrapper) > 0){
            return ResponseResult.failure(ResponseCode.STATUS_ERROR);

        }
        if (userMapper.insert(DtoPoMapper.INSTANCE.toUser(stu)) > 0){
            return ResponseResult.success(ResponseCode.STATUS_SUCCESS);
        }
        return ResponseResult.failure(ResponseCode.STATUS_ERROR);
    }

    @Override
    public JSONObject selectMySubmit(HttpServletRequest request) {

        List<SubmitDetail> submitDetails = userMapper.selectSubmitByUid(TokenUtil.getId(request));
        return ResponseResult.success(submitDetails);
    }

    @Override
    public JSONObject updatePassWordById(HttpServletRequest request, String pwd) {
        if (StringUtil.isEmptyOrNull(pwd)){
            return ResponseResult.failure("传入密码为空",ResponseCode.STATUS_ERROR);
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (userMapper.updatePassWordById(TokenUtil.getId(request),bCryptPasswordEncoder.encode(pwd)) > 0){
            return ResponseResult.success("更新成功");
        }
        return ResponseResult.failure("更新失败",ResponseCode.STATUS_ERROR);
    }
}
